package com.cht.commonUtil.quartz.chkin;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.impl.matchers.GroupMatcher;

import com.cht.commonUtil.enums.QuartzJobStatus;
import com.cht.commonUtil.quartz.QuartzChkinJob;
import com.cht.commonUtil.widgets.Widgets;

public class ApproveQuartz extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		/*
		 * 創建排程 ( 同時要利用jobDataMap把些資訊給job )
		 * 修改待辦事項
		 * 修改排程記錄的狀態
		 * */
		boolean isApprove = Integer.parseInt(request.getParameter("isApprove"))==1?true:false;	//主管是否同意
		int toDoListId = Widgets.getParNumberFromRequest( request.getParameter("toDoListId") );
		int quartzJobId = Widgets.getParNumberFromRequest( request.getParameter("quartzJobId") );
		String empId = request.getParameter("empId");
		String actType = request.getParameter("actType");
		
		String sql;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = Widgets.getConn();
			/****檢查有沒有其它主管先回覆了****/
			sql="SELECT status,cronString,subsysId FROM quartzjob WHERE quartzJobId=?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, quartzJobId);
			rs = ps.executeQuery();
			rs.next();
			int status = rs.getInt(1);
			String cronString = rs.getString("cronString");
			String subsysId = rs.getString("subsysId");
			if ( rs !=null ) {rs.close();}
			if ( ps !=null ) {ps.close();}
			
			if ( status == QuartzJobStatus.APPROVING ) {	//表示仍處於待審的狀態
				long quartzId = 0L;
				status = (isApprove?QuartzJobStatus.ACTIVATED:QuartzJobStatus.REJECTED);
				
				//修改排程工作的狀態
				sql = "UPDATE quartzjob SET status=? WHERE quartzJobId=?";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, status);
				ps.setInt(2, quartzJobId);
				ps.executeUpdate();
				
				//刪除已完成的待辦事項，將其加入待辦清單
				Widgets.completedList(toDoListId, empId);
				
				if( isApprove ) {
					List<String> svnAP = Widgets.getSVN4SubsysConnInfo(subsysId, 4);	//SVN AP OL的連線資訊
					
					ServletContext ctx = request.getServletContext();
					Scheduler sched = (Scheduler)ctx.getAttribute("sched");
					
					if( "update".equalsIgnoreCase(actType) ) {
						//若是修改，需要刪除舊的排程
						sql = "SELECT quartzId FROM quartzjob WHERE quartzJobId=(SELECT originalQuartzJobId FROM quartzjob WHERE quartzJobId=?)";
						ps = conn.prepareStatement(sql);
						ps.setInt(1, quartzJobId);
						rs = ps.executeQuery();
						rs.next();
						long originalQuartzId = rs.getLong("quartzId");
						
						for (String groupName : sched.getJobGroupNames()) {
							if( subsysId.equalsIgnoreCase( groupName ) ) {
								for (JobKey jobKey : sched.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
									String jobName = jobKey.getName();
									if( String.valueOf( originalQuartzId ).equalsIgnoreCase( jobName ) ) {
										sched.deleteJob(jobKey);
										sql = "DELETE FROM quartzjob WHERE quartzId=?";
										ps = conn.prepareStatement(sql);
										ps.setLong(1, originalQuartzId);
										ps.execute();
									}
								}	
							} 
						}
					}
					
					
					quartzId = System.currentTimeMillis();
					JobDataMap jdm = new JobDataMap();
					jdm.put("subsysId", subsysId);
					jdm.put("svnUrl", svnAP.get(0) );
					jdm.put("svnPath", "trunk");
					JobDetail jd = newJob(QuartzChkinJob.class).withIdentity( String.valueOf( quartzId ), subsysId ).setJobData(jdm).build();
					CronTrigger trigger = newTrigger().withIdentity(String.valueOf( quartzId ), subsysId).withSchedule(cronSchedule( cronString )).build();
					sched.scheduleJob(jd, trigger);
					
					sql = "UPDATE quartzjob SET quartzId=? WHERE quartzJobId=?";
					ps = conn.prepareStatement(sql);
					ps.setString(1, String.valueOf( quartzId ) );
					ps.setInt(2, quartzJobId);
					ps.executeUpdate();
				}
			}
		} catch(Exception e) {
			Widgets.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}
			} catch (Exception e) { e.printStackTrace(); }
		}
	}
}
